﻿@page "/counter"
@using System.IO;
@using Blazor.FileReader
@inject IFileReaderService fileReaderService;

<h1>Counter</h1>

<p>Current count: @currentCount</p>
<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

<div class="m-2">
    <h3>Read file test</h3>
    <input type="file" ref="inputTypeFileElement" accept=".fpn"/>
    <button onclick="@ReadFile" class="btn btn-info">Read file</button>
    
    @if (fileContent != null)
    {
        <p>Line Count: @fileContent.Count</p>
        <pre class="border border-primary">
        @foreach (var line in fileContent.Take(20))
        {
            <span>@line</span>
        }
        </pre>
    }
</div>


@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }

    IFileReaderRef readerRef;
    ElementRef inputTypeFileElement;
    List<string> fileContent;

    protected override void OnAfterRender()
    {
        base.OnAfterRender();
        readerRef = fileReaderService.CreateReference(inputTypeFileElement);
    }

    public async Task ReadFile()
    {

        /*
        foreach (var file in await fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync())
        {
            //// Read into buffer and act (uses less memory)
            //using (var stream = await file.OpenReadAsync())
            //{
            //    // Do stuff with stream...
            //    //await stream.ReadAsync(buffer, ...);
            //    // This following will fail. Only async read is allowed.
            //    //stream.Read(buffer, ...)
            //}

            // Read into memory and act
            using (var memoryStream = await file.CreateMemoryStreamAsync(4096))
            {
                // Sync calls are ok once file is in memory
                //memoryStream.Read(buffer, ...)
            }
        }
        */

        var selectedFile = (await fileReaderService.CreateReference(inputTypeFileElement)
            .EnumerateFilesAsync()).FirstOrDefault();
        if (selectedFile == null)
            return;

        var fileStream = await selectedFile.CreateMemoryStreamAsync(4096);

        var allLines = new List<string>();
        using (var streamReader = new StreamReader(fileStream))
        {
            var line = await streamReader.ReadLineAsync();
            while (line != null)
            {
                allLines.Add(line);
                line = await streamReader.ReadLineAsync();
                //Console.Write(".");
            }
        }

        this.fileContent = allLines;
    }


}
